import Echart from '@plugin/echarts'
import Empty from '@antd/empty'
import jgImg 	from '@img/quality/jg.png'
import jjImg 	from '@img/quality/jj.png'
import pImg 	from '@img/quality/print.svg'
 
const { $fn } = window

const Index = ({ rawData = {}, height = 300 }, ref)=>{
	const color = ['#2da2bf','#fd885c','##6a30fc','#fcc279','#e15efa','#4fab40','#fe7ffe','#00a9a4','#fdc31a']
	const symbol = ['circle', 'roundRect', 'triangle', 'diamond', 'pin', 'rect', 'circle', 'rect', 'roundRect']
	const formatData = []
	const legendData = []
	const { data, result_avg, x, y, info } = rawData
	let option = {}
	const print = () => {
		const Iframe = document.createElement('iframe')
		const src = window.myEcharts?.getDataURL({pixelRatio: 2, excludeComponents: ['toolbox', 'dataZoom']})
		const rule = [[], []]
		const dateRange = info.start_date + ' ~ ' + info.end_date
		let dateValueStr = ''
		const title = $fn.getUser()?.company.slice(0,2)
		let stats = `
			<table style='margin: 10px;'>
				<thead>
					<tr>
						<th>水平</th>
						<th>当月靶值</th>
						<th>固定靶值</th>
						<th>变异系数</th>
						<th>标准差</th>
					</tr>
				</thead>
				<tbody>
		`
		if (info.rules.length) {
			info.rules.forEach(({name, value}) => {
				if (value === '-1') {
					rule[0].push(name)
				} else {
					rule[1].push(name)
				}
			})
		}
		if (info.stat.length) {
			info.stat.forEach(({level, avg, cv, sd}) => {
				stats += `<tr>
					<td>水平${level || '--'}</td>
					<td>${avg || '--'}</td>
					<td>${result_avg[`level${level}_value_avg`] || '--'}</td>
					<td>${cv || '--'}</td>
					<td>${sd || '--'}</td>
				</tr>`
			})
		}
		stats += `
			</tbody>
		</table>
		`
		if (data.length) {
			const dateValue = []
			data.forEach(({data, level}, i) => {
				const formData = []
				dateValue[i] = {level, date: []}
				data.forEach(({date, value}, i) => {
					const d = date.split('-')
					// if (i === 0) {
						formData.push({date: parseInt(d[1]) + '-' + parseInt(d[2]), value})
					// } else {
					// 	formData.push({date: parseInt(d), value})
					// }
				})
				dateValue[i]['date'].push(...formData)
			})
			dateValue.forEach(({level, date}) => {
				let str = ''
				date.forEach(({date, value}, i) => {
					str += `<div style='display:flex;flex-direction: column;border: 1px solid #000;text-align: center;margin: 5px -1px 0 0;'>
						<span>${date}</span>
						<span style='border-top: 1px solid #000;min-width: 42px;'>${value}</span>
					</div>`
				})
				dateValueStr += `
					<div style='margin: 10px;'>
						<div>水平${level}的数据：</div>
						<div style='display: flex;flex-wrap: wrap;'>
							${str}
						</div>
					</div>
				`
			})
		}
		Iframe.style.cssText = 'position:fixed;width:100%;height:100%;z-index:9;left:200%;background:#fff;'
		document.body.appendChild(Iframe)
		// <style>
		// 	@media print {
		// 		@page{margin: 10px;size: A4 landscape;}
		// 		body{ -webkit-print-color-adjust:exact;-moz-print-color-adjust:exact;-ms-print-color-adjust:exact;print-color-adjust:exact;}
		// 		span{flex: 1;}
		// 	}
		// </style>
		Iframe.contentDocument.body.innerHTML = `
		<style>
			body {margin: 0;padding: 10px;}
			table {border: 1px solid #000000;border-collapse: collapse;}
			th, td {border: 1px solid #000000;text-align: center;font-weight: 400;}
			td {padding: 0 10px;}
		</style>
		<div style='font-weight: 400;font-size: 12px;box-sizing: border-box;display: flex;flex-direction: column;justify-content: space-between;height: 100%;'>
			<div style='display: flex;flex-direction: column;'>
				<div  style='display: flex;align-items: center;margin-bottom: 10px;font-weight: 700;font-size: 16px;width: 100%;justify-content: center;'>
					${title}诺森实验室质量控制图
				</div>
				<div style='display:flex;margin: 0 10px 10px 10px;'>
					<span style='width: 33.3%'>控制品名称：${info.control_name || '--'}控制品名称控制品名称控制品名称</span>
					<span style='width: 33.3%'>分析物：${info.analyte_name || '--'}</span>
					<span style='width: 33.3%'>试剂盒：${info.instrument_kit_name || '--'}</span>
				</div>
				<div style='display:flex;margin: 0 10px 10px 10px;'>
					<span style='width: 33.3%'>批号：${info.master_lot_number || '--'}</span>
					<span style='width: 33.3%'>批号有效期：${info.expiration_date || '--'}</span>
					<span style='width: 33.3%'>试剂批号：${info.reagent_lot_number || '--'}</span>
				</div>
				<div style='display:flex;margin: 0 10px 10px 10px;'>
					<span style='width: 33.3%'>试剂类型：${info.reagent_type_name || '--'}</span>
					<span style='width: 33.3%'>单位：${info.unit_name || '--'}</span>
					<span style='width: 33.3%'>方法：${info.method_name || '--'}</span>
				</div>
				<div style='display:flex;margin: 0 10px 10px 10px;'>
					<span style='width: 33.3%'>设备名称：${info.device_name || '--'}</span>
					<span style='width: 33.3%'>设备编号：${info.device_number || '--'}</span>
					<span style='width: 33.3%'>靶值范围：${dateRange || '--'}</span>
				</div>
				<div style='display:flex;margin: 0 10px 10px 10px;'>
					<span style='width: 33.3%'>厂商：${info.manufacturer || '--'}</span>
					<span style='width: 33.3%'>基质：${info.matrix_name || '--'}</span>	
					<span style='width: 33.3%'>温度：${info.temperature || '--'}</span>
				</div>
				${info.result_type === '1' ? stats : ''}
				${dateValueStr}
				${info.rules.length ? `<div style='display: flex;align-items: center;margin: 0 10px 10px 10px;'>
					<span>使用规则：${rule[1].map(v => ` ${v}(w)`)}${rule[1].length && ','}${rule[0].map(v => ` ${v}`)}</span>
				</div>` : ''}
				<div style='margin-top:20px;'>
					<img alt='' src=${src} style='width: 100%' />
				</div>
			</div>
			<div style='display: flex;flex-direction: column;'>
				<div style='margin-top:20px;margin:0 10px 100px 10px;'>
					质控评价：
				</div>
				<div style='display:flex;margin: 0 10px 60px 10px;'>
					<span style='width:33.3%'>评价人：</span>
					<span style='width:33.3%'>审核人：</span>
					<span style='width:33.3%'>批准人：</span>
				</div>
			</div>
		</div>`
		setTimeout(() => Iframe.contentWindow.print())
		setTimeout(() => document.body.removeChild(Iframe))
	}
	if ($fn.hasArray(data)) {
		const formatColor = data.length === 1 ? [color[data[0].level - 1]] : color
		const formatX = [...new Set(x.map(v => v.split(' ')[0]))]
		let formatAvg = (function(){
			const start = result_avg?.start_date?.split(' ')[0] ?? ''
			const end = result_avg?.end_date?.split(' ')[0] ?? ''
			const avg = [{
				xAxis: start,
				label: {
					position: 'end',
					formatter: result_avg?.level_avg ?? ''
				}
			}]
			if (!(start === end)) {
				avg.push({
					xAxis: end,
					label: {
						position: 'end',
						formatter: result_avg?.level_avg ?? ''
					}
				})
			}
			return avg
		})()
		data.forEach(({data: items, level}) => {
			const markPointData = []
			const dottedList = []
			const solidList = []
			items.forEach((v, i) => {
				if (v.rule.length) {
					dottedList.push(v)
					solidList.push('')
				} else {
					dottedList.push('')
					solidList.push(v)
				}
			})
			solidList.forEach((v, i) => {
				if (!v) {
					if (-1 !== i -1 && !dottedList[i-1]?.rule) {
						dottedList[i-1] = solidList[i-1]
					}
					if (dottedList.length !== i + 1 && !dottedList[i+1]?.rule) {
						dottedList[i+1] = solidList[i+1]
					}
				}
			})
			dottedList.forEach(v => {
				if (v?.rule?.length) {
					markPointData.push({
						coord: [v.date.split(' ')[0], v.z],
						value: v.value,
						label: {
							color: '#FFFFFF',
							fontWeight: 'lighter',
							fontSize: 10,
						},
						itemStyle: {
							color: '#FF0000'
						},
						symbolSize: [45, 45]
					})
				}
			})
			formatData.push({
				name: `水平${level}`,
				type: 'line',
				symbol: symbol[level - 1],
				symbolSize: 6,
				lineStyle: {
					color: color[level - 1]
				},
				data: solidList.map(v => ({
					value: v ? [v.date.split(' ')[0], v.z > +y['3sd'] ? +y['3sd'] + 0.2 : v.z < +y['-3sd'] ? +y['-3sd'] - 0.2 : v.z, v.rule, v.z] : '',
					itemStyle: {
						color: color[level - 1]
					}
				}))
			})
			formatData.push({
				name: `水平${level}`,
				type: 'line',
				symbol: symbol[level - 1],
				symbolSize: 6,
				lineStyle: {
					color: color[level - 1]
				},
				markPoint: {
					data: markPointData
				},
				smooth: false,
				itemStyle:{
					normal:{
						lineStyle:{
							with:2,
							type:'dotted'  //'dotted'虚线 'solid'实线
						}
					}
				}, 
				data: dottedList.map(v => ({
					value: v ? [v.date.split(' ')[0], v.z > +y['3sd'] ? +y['3sd'] + 0.2 : v.z < +y['-3sd'] ? +y['-3sd'] - 0.2 : v.z, v.rule, v.z] : '',
					itemStyle: {
						color: v?.rule?.length ? '#FF0000' : color[level - 1],
					}
				}))
			})
			
			legendData.push({name: `水平${level}`, icon: symbol[level - 1], itemStyle: {color: color[level - 1]}})
		})
		option = {
			toolbox: {
				show: true,
				feature: {
					// saveAsImage: {
					// 	title: '导出为图片'
					// },
					myPrint: {
						show: true,
						title: '打印',
						onclick: () => print(),
						icon: `image://${pImg}`
					}
				},
				right: '22px'
			},
			tooltip: {
				trigger: 'axis',
				backgroundColor: 'rgba(255,255,255,.9)',
				borderColor: '#E5E9F2',
				borderWidth: 1,
				textStyle: {
					color: '#555',
					fontSize: 12,
					lineHeight: 56
				},
				padding: 8,
				formatter: param => {
					let res = `<div>${param[0].axisValueLabel}</div>`
					let strObj = {}
					let valMap = {}
					for (let i = 0; i < param.length; i++) {
						const { seriesName, value: [value, rule, sourceValue] } = param[i]
						const warning = []
						const stop = []
						if (!value) continue
						if (valMap[seriesName] === value) continue
						rule?.length && rule.forEach(({name, value}) => {
							if (value === 1) {
								warning.push(name)
							} else {
								stop.push(name)
							}
						})
						strObj = {...strObj, [seriesName]:  strObj[seriesName] ? [...strObj[seriesName], {value: sourceValue, rule: {warning, stop}}] : [{value: sourceValue, rule: {warning, stop}}] } 
						valMap[seriesName] = value
					}
					for(const key in strObj) {
						res += `<div class='mtb5 fxm' style='vertical-align: middle;'>
							<i style='display:inline-block;width:10px;height:10px;background-color:${color[key.slice(-1) - 1]};border-radius:50%;'></i>
							<div class='ml5 mr10 fxm'>${key}:${strObj[key]?.map(({value, rule: {warning, stop}}) => ` ${value}${warning.length ? ` <img class='ml5' src=${jgImg} style='width:10px;height:10px;' alt='' />:[${warning.map(v => v)}]` : ''}${stop.length ? ` <img class='ml5' src=${jjImg} style='width:10px;height:10px;' alt='' />:[${stop.map(v => v)}]` : ''}` )}</div>
						</div>`
					}
					return res
				}
			},
			legend: {
				orient: 'horizontal',
				itemWidth:12,
				itemHeight:12,
				itemGap:15,
				textStyle:{
					fontSize:12,
					color:'#999'
				},
				data: legendData
			},
			grid: {
				top: '45px',
				left: '40px',
				right: '20px',
				bottom: '20px',
				containLabel: true
			},
			color: formatColor,
			xAxis: {
				// type: 'time',
				// axisLabel: {
				// 	formatter: '{MM}月{dd}日'
				// },
				// splitNumber: formatX.length,
				type: 'category',
				data: formatX,
				axisTick: {
					show: false
				}
			},
			yAxis: {
				type: 'value',
				axisTick: {
					show: false
				},
				splitLine: {
					show: false
				},
				min: +y['-4sd'],
				max: +y['4sd'],
				axisLabel: {
					formatter: ''
				}
			},
			dataZoom: [{
				type: 'inside',
				xAxisIndex: 0,
				brushSelect: false,
				startValue: 0,
				endValue: 30,
				// minValueSpan: 30, // 可显示范围
				// maxValueSpan : 30,
				zoomLock: true, //是否锁定数据窗口的大小
				height: 20,
				left: '10%',
				right: '10%',
				top: 240,
			}],
			series: [...formatData, {
				type: 'line',
				markLine: {
					label: {
						show: true,
						position: 'start'
					},
					symbol: ['none', 'none'],
					silent: true,
					data: [
						{
							yAxis: +y['4sd'],
							label: {
								formatter: ''
							},
							lineStyle: {
								type: 'solid'
							}
						},
						{
							yAxis: +y['3sd'],
							label: {
								formatter: '+3sd'
							}
						},
						{
							yAxis: +y['2sd'],
							label: {
								formatter: ''
							}
						},
						{
							yAxis: +y['1sd'],
							label: {
								formatter: ''
							}
						},
						{
							yAxis: +y['x'],
							label: {
								formatter: '均值'
							}
						},
						{
							yAxis: +y['-1sd'],
							label: {
								formatter: ''
							}
						},
						{
							yAxis: +y['-2sd'],
							label: {
								formatter: ''
							}
						},
						{
							yAxis: +y['-3sd'],
							label: {
								formatter: '-3sd'
							}
						},
						{
							yAxis: +y['-4sd'],
							label: {
								formatter: ''
							},
							lineStyle: {
								type: 'solid'
							}
						},
						...formatAvg
					]
				}
			}]
		}
	}
	return (
		<div className='rel fxmc' style={{height}}>
			{
				$fn.hasArray(data) ? <Echart option={option} /> : <Empty data={[]} />
			}
		</div>
	)
}
	
export default Index